<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AdminMenu extends Model
{
    use HasFactory;

    protected $attributes = [
        'icon'   => '',
        'hidden' => '10',
        'sort'   => 99,
    ];

    public $fillable = [
        'title',
        'path',
        'sort',
        'parent_id',
        'icon',
        'hidden'
    ];

    public function setParentIdAttribute($value)
    {
        $this->attributes['parent_id'] = (int)($value);
    }

    /**
     * 可以访问当前菜单的角色 [定义正向多对多关联]
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function roles()
    {
        return $this->belongsToMany(AdminRole::class, 'admin_role_menu', 'menu_id', 'role_id');
    }

    /** 给用户新增角色
     * @param array $roleArray
     * @param object $user
     * @return mixed
     */
    public function addRoles(array $roleArray = [],object $user)
    {
        // 移除用户的所有角色...
        $user->roles()->detach();

        // 新增用户角色
        $roels = [];
        foreach ($roleArray as $roleId) {
            $roels[$roleId] = [
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];
        }
        return $user->roles()->sync($roels);
    }
}
